<script setup lang="ts">
import { modalTableConfig } from './config/table-config';
import { formConfig } from './config/form-config';
import { handleDelKey, transformDataToKeys, transformValue } from '@/utils';
import { generateNameToLevel } from '@/config/constant';
import { doGetProcessDetail } from '@/api/modeling/ProcessManagement/index';
import { ArrowUp, ArrowDown } from '@element-plus/icons-vue';
import type {
    ProcessListModal,
    TechnologicalProcessDTO,
    WorkingProcedureEquipmentDTO
} from '@/api/modeling/ProcessManagement/model/type';

interface ProcessRouteForm {
    [key: string]: string | null;
    processRouteCode: string | null;
    processRouteName: string | null;
    processRouteDesc: string | null;
    materialCode: string | null;
    remarks: string | null;
}

const initProcessRouteForm = () => {
    return {
        processRouteCode: null,
        processRouteName: null,
        processRouteDesc: null,
        materialCode: null,
        remarks: null
    };
};

const processRouteForm = ref<ProcessRouteForm>(initProcessRouteForm());

/**
 * 新增/编辑
 */
const { visible, loading, modalSlotRef, handleFullscreen, getMaxHeight } = useModal({
    appendData: processRouteForm
});

const open = (id: string) => {
    visible.value = true;
    isExpand.value = true;
    initData(id);
};

const handleOk = () => {
    visible.value = false;
};

/**
 * 编辑状态，初始化数据
 */
const processCodeDisabled = ref(false);
const initData = async (id: string) => {
    try {
        const { data } = await doGetProcessDetail(id);
        if (data) {
            handleInitEditData(data);
            processCodeDisabled.value = true;
        }
    } catch (error) {
        console.error(error);
    }
};

/**
 * 处理编辑初始化数据
 */
const processRouteId = ref();
const handleInitEditData = (data: ProcessListModal) => {
    processRouteId.value = data.id; // 工艺路线id
    modalSlotRef.value.setInit(false); // 取消默认表格添加行
    processMaterialId.value = data.materialId; // 初始化选中物料编码 id
    processMaterialCode.value = data.materialCode; // 初始化选中物料编码

    processRouteForm.value = {
        ...transformDataToKeys<ProcessListModal>(data, [
            'processRouteCode',
            'processRouteName',
            'processRouteDesc',
            'materialCode',
            'remarks'
        ])
    };

    // 设置表格数据，对  data.technologicalProcess  数组进行转换，生成新的  tableData  数组
    const tableData = data.technologicalProcess?.map((item: TechnologicalProcessDTO) => {
        // 过滤无用参数
        const processEquipments =
            item.processEquipments?.map(i =>
                handleDelKey(i, ['id', 'materialId', 'processProcessId'])
            ) ?? [];

        markSameEquipment(processEquipments);

        return {
            ...handleDelKey(item, ['processEquipments']),
            edit: true,
            unAction: true,
            processEquipments
        };
    });

    modalSlotRef.value.setTableData(tableData);
};

// 选择物料编码，点击保存
const processMaterialId = ref(); // 工序 id
const processMaterialCode = ref(); // 工序编码

/**
 * 标记当前相同加工设备不同辅助资源数据
 */
const markSameEquipment = (list: WorkingProcedureEquipmentDTO[]) => {
    const markMap = new Map(); // 关系映射
    list.map(item => {
        if (!markMap.get(item.equipmentCode)) {
            item.show = true;
            markMap.set(item.equipmentCode, true);
        }
    });
};

/**
 * 收起/展开
 */
interface FormItems extends ItemConfig {
    hidden?: boolean;
}
const isExpand = ref(true);
const formItems = ref<FormItems[]>(formConfig.items);
watch(
    () => isExpand.value,
    val => {
        if (val) {
            formItems.value.forEach(item => (item.hidden = false));
        } else {
            formItems.value.forEach((item, index) => {
                if (!index) {
                    item.hidden = false;
                } else {
                    item.hidden = true;
                }
            });
        }
    }
);

defineExpose({
    open
});
</script>

<template>
    <q-modal
        v-model:visible="visible"
        title="查看"
        :fullscreen="true"
        :confirm-loading="loading"
        :style="{ top: '20px' }"
        :hide-cancel-btn="true"
        width="1000px"
        ok-text="关闭"
        @ok="handleOk"
        @fullscreen="handleFullscreen"
    >
        <div :id="generateNameToLevel('4')" class="m-process__page">
            <q-form-item :id="formConfig.id!" class="form-placeholder"></q-form-item>
            <el-row :gutter="32" class="m-b-24">
                <el-col
                    v-for="item in formItems"
                    :key="item.validProps?.id"
                    :span="12"
                    class="role-main__header form-common m-b-18"
                    :style="{ display: item.hidden ? 'none' : 'block' }"
                >
                    <label class="is-column">
                        <span v-if="item.validProps?.required">*</span>
                        {{ item.columnProps?.label }}:
                    </label>
                    <q-form-item
                        v-if="!item.itemType || item.itemType === 'text'"
                        :id="item.validProps?.id!"
                    >
                        <el-input
                            v-model="processRouteForm[item.modelKey!]"
                            :placeholder="`请输入${item.columnProps?.label}`"
                            disabled
                            v-bind="item.elInputProps"
                        />
                    </q-form-item>
                    <q-form-item v-else-if="item.itemType === 'other'" :id="item.validProps?.id!">
                        <q-virtual-select
                            v-model="processRouteForm[item.modelKey!]"
                            disabled
                            placeholder="请选择物料编码"
                        />
                    </q-form-item>
                </el-col>
                <el-col :span="12" class="m-but"
                    ><span @click="isExpand = !isExpand"
                        >{{ isExpand ? '收起' : '展开'
                        }}<el-icon v-if="isExpand" class="u-icon"><ArrowUp color="#06f" /></el-icon>
                        <el-icon v-else class="u-icon"><ArrowDown color="#06f" /></el-icon>
                    </span>
                </el-col>
            </el-row>
            <base-table
                :id="generateNameToLevel('1')"
                ref="modalSlotRef"
                :max-height="getMaxHeight"
                :add-table-row="false"
                :tableConfig="modalTableConfig"
                :modal-mode="true"
                :show-setting="false"
                :show-page="false"
                :un-action="true"
            >
                <!-- 工序号 -->
                <template #index>
                    <el-table-column type="index" label="工序号" width="100">
                        <template #default="{ $index }"
                            ><span class="l-h-32">{{ $index + 1 }}</span></template
                        >
                    </el-table-column>
                </template>
                <!-- 工序编码 -->
                <template #processCode="{ row }">
                    <q-virtual-select v-model="row.processCode" disabled placeholder="请选择" />
                </template>
                <!-- 工序名称 -->
                <template #processName="{ row }">
                    <span class="l-h-32">{{ row.processName || '--' }}</span>
                </template>
                <!-- 加工设备 -->
                <template #workingProcedureEquipments="{ row }">
                    <template v-for="item in row.processEquipments" :key="item.equipmentId">
                        <q-tooltip
                            :content="transformValue(item.equipmentCode)"
                            :class="['l-h-32', 'p-b-6', { 'is-hide': !item.show }]"
                        />
                    </template>
                </template>
                <!-- 辅助资源 -->
                <template #workingProcedureAuxiliary="{ row }">
                    <template v-for="item in row.processEquipments" :key="item.auxiliaryId">
                        <q-tooltip
                            :content="transformValue(item.auxiliaryDataCoding)"
                            class="l-h-32 p-b-6"
                        />
                    </template>
                </template>
                <!-- 加工批量 -->
                <template #workingProcedureList1="{ row, item }">
                    <template v-if="row.processEquipments">
                        <q-form-item
                            v-for="auxiliary in row.processEquipments"
                            id="1"
                            :key="auxiliary.auxiliaryId"
                            class="p-b-6"
                        >
                            <el-input-number
                                v-model="auxiliary.processingBatch"
                                placeholder="请输入"
                                :controls="false"
                                :precision="0"
                                :min="1"
                                disabled
                                v-bind="item.elInputNumberProps"
                            />
                        </q-form-item>
                    </template>
                    <template v-else>--</template>
                </template>
                <!-- 生产节拍 -->
                <template #workingProcedureList2="{ row, item }">
                    <template v-if="row.processEquipments">
                        <q-form-item
                            v-for="auxiliary in row.processEquipments"
                            id="2"
                            :key="auxiliary.auxiliaryId"
                            class="p-b-6"
                        >
                            <el-input-number
                                v-model="auxiliary.productionBeat"
                                placeholder="请输入"
                                :controls="false"
                                :precision="0"
                                :min="1"
                                disabled
                                v-bind="item.elInputNumberProps"
                            />
                        </q-form-item>
                    </template>
                    <template v-else>--</template>
                </template>
            </base-table>
        </div>
    </q-modal>
</template>

<style lang="scss" scoped>
@include b(m-expand) {
    @include e(list) {
        @include flex(flex-end);

        border-bottom: 1px solid #eee;
    }

    @include e(form) {
        @include m(item) {
            box-sizing: border-box;
            padding: 8px 12px;

            :deep() {
                .el-input-number {
                    width: 99%;
                }
            }
        }
    }

    @include e(text) {
        box-sizing: border-box;
        padding: 0 12px;
    }
}

@include b(m-but) {
    @include flex(flex-start);

    margin-top: 10px;
    font-size: 14px;
    color: var(--q-color-primary);

    & > span {
        display: inline-block;
        padding: 8px 15px;
        cursor: pointer;
        border-radius: 4px;

        &:hover {
            background-color: var(--el-fill-color-light);
        }
    }
}

@include b(is-hide) {
    visibility: hidden;
}

@include b(u-icon) {
    position: relative;
    top: 2px;
    margin-left: 4px;
}

.m-process__page {
    flex: 1;

    :deep() {
        .row-expand--cover {
            .el-table__expand-icon {
                display: none;
            }
        }

        .el-table__expanded-cell {
            padding: 0;
        }

        .el-table .el-table__cell {
            vertical-align: top;
        }

        .el-table__body-wrapper .el-table-column--selection .el-checkbox {
            position: relative;
            top: 4px;
        }

        .m-table__header {
            position: sticky;
            top: 55px;
            z-index: 11;
            width: 100%;
        }

        .header-sticky .el-table__header-wrapper {
            top: 95px;
        }

        .is-fullscreen {
            .m-table__header {
                top: -7px;
            }

            .header-sticky .el-table__header-wrapper {
                top: 32px;
            }

            .m-table__errMsg {
                top: 25px;
            }
        }

        .m-table__errMsg {
            position: sticky;
            top: 88px;
            z-index: 111;
        }
    }
}
</style>
